package com.smile.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smile.common.utils.PageUtils;
import com.smile.common.utils.Query;
import com.smile.product.dao.CategoryDao;
import com.smile.product.entity.CategoryEntity;
import com.smile.product.service.CategoryService;
import com.smile.product.vo.CateLog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {
@Autowired
private StringRedisTemplate redisTemplate;
@Autowired
private RedissonClient redissonClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //查出所有分类
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        //组装成父子树形结构
        //找到所有一级分类
        List<CategoryEntity> ListMenu1 = categoryEntities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, categoryEntities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return ListMenu1;
    }

    //递归查询所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return root.getCatId() == categoryEntity.getParentCid();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

    // 数据库修改时更新缓存
//    @Caching(evict = {
//            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
//            @CacheEvict(value = "category",key = "'getLevel1Categorys'")
//    })
    // @CacheEvict(value = "category",key = "'tLevel1Categorys'")
    @Cacheable({"category"})
    //查询所有一级分类
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return  baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid",0));
    }
    @Override
    public Map<String, List<CateLog2Vo>> getCatalogJson(){
           return  getCatalogJsonFromLock();

    }
    //分布式锁
    private Map<String, List<CateLog2Vo>> getCatalogJsonFromLock(){
//        String lua = "if redis.call('get',KEYS[1]) == ARGV[1] then " +
//                "return redis.call('del',KEYS[1]); " +
//                "else " +
//                "return 0; " +
//                "end; ";
//        String uuid = UUID.randomUUID().toString();
//        //1.占分布锁，去redis占坑 此时lock和过期时间具有原子性
//        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid,30, TimeUnit.SECONDS);
//        System.out.println(lock);
//        if(lock){

            //加锁成功 执行业务
            //设置过期时间
//            redisTemplate.expire("lock",30, TimeUnit.SECONDS);
            RLock lock = redissonClient.getLock("CataLogJson-lock");
            lock.lock();
            Map<String, List<CateLog2Vo>> catalogJsonFromCache;

            try {
                catalogJsonFromCache = getCatalogJsonFromCache();
            }finally {
                //原子性删锁
//                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(lua, Long.class), Arrays.asList("lock"), uuid);
                lock.unlock();
            }
            return catalogJsonFromCache;
            //查询和删除必须为原子操作
//            if(uuid.equals(redisTemplate.opsForValue().get("locak"))) {
//                redisTemplate.delete("lock");
//            }
//        }else{
//            return getCatalogJsonFromLock();
//        }
    }

    //从缓存中获取分类信息
    private Map<String, List<CateLog2Vo>> getCatalogJsonFromCache(){
        //从redis中读取分类判断是否存在
        String categoryJson = redisTemplate.opsForValue().get("categoryJson");
        if(StringUtils.isEmpty(categoryJson)){
            //如果为空从将数据库查询到的数据放入redis
            Map<String, List<CateLog2Vo>> catalogJsonFromDB = getCatalogJsonFromDB();
            //将查询到的数据转换为json格式存入
            String jsonString = JSON.toJSONString(catalogJsonFromDB);
            redisTemplate.opsForValue().set("categoryJson",jsonString);
            //返回查询到的数据
            return catalogJsonFromDB;
        }else {
            //对取出的数据进行格式转换
            Map<String, List<CateLog2Vo>> cateLog2Vos = JSON.parseObject(categoryJson, new TypeReference< Map<String, List<CateLog2Vo>>>(){});
            return cateLog2Vos;
        }
    }

    //从数据库中查询所有分类
    private Map<String, List<CateLog2Vo>> getCatalogJsonFromDB() {
        //查出所有分类
        List<CategoryEntity> categoryAll = baseMapper.selectList(null);
        //查询所有一级分类
        List<CategoryEntity> level1Categorys = getLevel1Categorys();
        Map<String, List<CateLog2Vo>> parentCid = level1Categorys.stream().collect(Collectors.toMap(
                k -> k.getCatId().toString(),
                //查询一级分类对应的二级分类
                v -> {
                    List<CategoryEntity> level2Categorys = getParentCid(categoryAll,v.getCatId());
                    List<CateLog2Vo> cateLog2VoList = null;
                    if (null != level2Categorys) {
                        cateLog2VoList = level2Categorys.stream().map(l2 -> {
                            CateLog2Vo cateLog2Vo = new CateLog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                            List<CategoryEntity> level3Categorys = getParentCid(categoryAll,l2.getCatId());
                            if(null!=level3Categorys){
                                List<CateLog2Vo.CateLog3Vo> collect = level3Categorys.stream().map(l3 -> {
                                    CateLog2Vo.CateLog3Vo cateLog3Vo = new CateLog2Vo.CateLog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                                    return cateLog3Vo;
                                }).collect(Collectors.toList());
                                cateLog2Vo.setCatalog3List(collect);
                            }
                            return cateLog2Vo;
                        }).collect(Collectors.toList());
                    }
                    return cateLog2VoList;
                }));
                return  parentCid;
        }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> categoryAll,long parentCid) {
        List<CategoryEntity> collect = categoryAll.stream()
                .filter(item -> item.getParentCid() == parentCid).collect(Collectors.toList());
        return collect;
    }
}